package com.xcity.util;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcity.config.ConfigEx;
import com.xcity.db.entity.Player;
import com.xcity.db.entity.User;
import com.xcity.game.account.AccountChannel;
import com.xcity.game.account.AccountService;
import com.xcity.game.common.MessageConst;
import com.xcity.game.player.cache.PlayerCacheService;

import naga.x.App;
import naga.x.util.CommonUtils;
import naga.x.util.IOUtils;
import naga.x.util.StringUtils;

public class PlatformApi {

	public static String resourceServerUrl;
	/** 礼包码兑换url */
	public static String codeUrl;
	/** 游戏金榜：检测是否关注了公众号 */
	public static String j9kgamesSubscribeUrl;
	/** 美图游戏：登录验证 */
	public static String meituLoginUrl;
	/** QQ玩吧：获取QQ好友 */
	public static String qqGetFriendsUrl;
	/** QQ玩吧：向QQ好友发送消息 */
	public static String qqSendMsgUrl;
	
	public static final Logger LOG = LoggerFactory.getLogger(PlatformApi.class);
	
	public static void init() {
//		String prefix = App.getApp().getConfig().getString(Config.PLATFORM_URL);
		ConfigEx config = App.getApp().getConfig();
		resourceServerUrl = StringUtils.requireNonEmpty(config.resourceServerUrl);
		
		String prefix = config.platformUrl;
		codeUrl = prefix + "/app/code";
		j9kgamesSubscribeUrl = prefix + "/99kgames/subscribe";
		meituLoginUrl = prefix + "/meitu/login";
		qqGetFriendsUrl = prefix + "/qzone/friends";
		qqSendMsgUrl = prefix + "/qzone/send_msg";
	}
	
	/**
	 * 渠道用户登录验证
	 * @param channel
	 * @param userId
	 * @param userName
	 * @param token
	 * @return
	 */
	public static String verifyLogin(AccountChannel channel, String userId, String userName, String token) {
		try {
			if (channel == AccountChannel.MEITU) {
				String res = HttpUtils.post(meituLoginUrl, new String[] {
						"serverId", String.valueOf(IdUtils.serverId),
						"userId", channel.withoutPrefix(userId),
						"userName", userName,
						"sessionId", token
						
				});
				JSONObject resObj = StringUtils.isNotEmpty(res) ? JSON.parseObject(res) : null;
				if (resObj == null) {
					return MessageConst.OP_TIME_OUT;
				}
				if (StringUtils.isEmpty(resObj.getString("uid"))) {
					String error = resObj.getString("msg");
					return StringUtils.isNotEmpty(error) ? error : MessageConst.OP_TIME_OUT;
				}
			}
			return null;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return MessageConst.OP_TIME_OUT;
	}
	
	public static List<Player> getQQFriends(Player player) {
		try {
			User account = player.getAccount();
			AccountChannel ac = account.getChannel();
			if (ac != AccountChannel.QQ_WANBA && ac != AccountChannel.QQ) {
				return null;
			}
			String res = HttpUtils.post(qqGetFriendsUrl, new String[] {
					"openid", ac.withoutPrefix(account.getChannelUid()),
					"openkey", account.getToken()
			});
			if (StringUtils.isEmpty(res)) {
				return null;
			}
			JSONObject resObj = JSON.parseObject(res);
			if (resObj == null || resObj.getIntValue("ret") != 0) {
				return null;
			}
			JSONArray openids = resObj.getJSONArray("items");
			if (openids == null) {
				return null;
			}
//			{
//				"ret":0,
//				"is_lost":0,
//				"items":[
//				{"openid":"9CE729C9927532BABBB57F6AB000925B"},
//				{"openid":"08B8273CACFBE0D9F57CAB4E7D8BDBF0"}
//				]
//			}
			AccountService accountService = App.getApp().getServiceManager().get(AccountService.class);
			PlayerCacheService cacheService = App.getApp().getServiceManager().get(PlayerCacheService.class);
			List<Player> friends = new ArrayList<Player>(openids.size());
			for (int i = 0; i < openids.size(); i++) {
				String openid = openids.getJSONObject(i).getString("openid");
				account = accountService.find(ac.withPrefix(openid));
				if (account != null && (player = cacheService.find(account.getDefaultPlayerId())) != null) {
					friends.add(player);
				}
			}
			return friends;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 向qq好友发送消息<br/>
	 * @param source 发送者（必须保证在线）
	 * @param target 接收者
	 * @param content
	 */
	public static void sendQQMsg(Player source, Player target, String content) {
//		if (!App.getApp().getServiceManager().get(RelationService.class).isQQFriend(source, target)) {
//			return;
//		}
		User acc = source.getAccount();
//		if (acc == null
//				|| (acc.getChannel() != AccountChannel.QQ_WANBA && acc.getChannel() != AccountChannel.QQ)) {
//			return;
//		}
//		if (RobotUtils.isRobot(target)) {
//			return;
//		}
		String openid = acc.getChannel().withoutPrefix(acc.getChannelUid());
		String openkey = acc.getToken();
		acc = target.getAccount();
		if (acc == null) { // maybe offline
			acc = App.getApp().getServiceManager().get(AccountService.class).findById(target.getUserId());
		}
//		if (acc == null
//				|| (acc.getChannel() != AccountChannel.QQ_WANBA && acc.getChannel() != AccountChannel.QQ)) {
//			return;
//		}
		String fopenid = acc.getChannel().withoutPrefix(acc.getChannelUid());
		HttpUtils.post(qqSendMsgUrl, new String[] {
				"openid", openid,
				"openkey", openkey,
				"fopenid", fopenid,
				"type", "3", // 1:pk, 2:送心, 3:自定义
				"content", content
		});
	}
	
	/**
	 * 头像映射
	 * @param channel
	 * @param icon
	 * @return 映射到图片缓存服务器的url
	 */
	public static String mappingIcon(AccountChannel channel, String icon) {
		if (StringUtils.isNotEmpty(icon)) {
			// 请求图片缓存服务器更新头像
			String url = resourceServerUrl + "/icon/update?channel=" + channel.name + "&url=" + CommonUtils.encodeURL(icon, IOUtils.UTF8);
			byte[] b = HttpUtils.request(url, HttpUtils.PUT, null, null);
			String id = b != null ? StringUtils.bytesToString(b, IOUtils.UTF8) : null;
			if (id != null && id.endsWith(channel.name)) {
				return resourceServerUrl + "/icon/" + id;
			}
		}
		return icon;
	}
	
}
